<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use think\Request;
/**
 * $string：字符串，明文或密文；
 * $operation：DECODE表示解密，ENCODE 表示加密
 * $key：密匙；
 * $expiry：密文有效期
*/
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
    // 动态密匙长度，相同的明文会生成不同密文就是依靠动态密匙
    $ckey_length = 4;
    // 密匙
    $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);
    // 密匙a会参与加解密
    $keya = md5(substr($key, 0, 16));
    // 密匙b会用来做数据完整性验证
    $keyb = md5(substr($key, 16, 16));
    // 密匙c用于变化生成的密文
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length):
        substr(md5(microtime()), -$ckey_length)) : '';
    // 参与运算的密匙
    $cryptkey = $keya.md5($keya.$keyc);
    $key_length = strlen($cryptkey);
    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) :
        sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
    $string_length = strlen($string);
    $result = '';
    $box = range(0, 255);
    $rndkey = array();
    // 产生密匙簿
    for($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }
    // 用固定的算法，打乱密匙簿，增加随机性.
    for($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    // 核心加解密部分
    for($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        // 从密匙簿得出密匙进行异或，再转成字符
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if($operation == 'DECODE') {
        // 验证数据有效性，请看未加密明文的格式
        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) &&
            substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        return $keyc.str_replace('=', '', base64_encode($result));
    }

}

/**
 * 获取指定年月日的开始时间戳和结束时间戳(本地时间戳非GMT时间戳)
 * [1] 指定年：获取指定年份第一天第一秒的时间戳和下一年第一天第一秒的时间戳
 * [2] 指定年月：获取指定年月第一天第一秒的时间戳和下一月第一天第一秒时间戳
 * [3] 指定年月日：获取指定年月日第一天第一秒的时间戳
 * @param  integer $year     [年份]
 * @param  integer $month    [月份]
 * @param  integer $day      [日期]
 * @return array('start' => '', 'end' => '')
 */
function getStartAndEndUnixTimestamp($year = 0, $month = 0, $day = 0)
{
    if(empty($year))
    {
        $year = date("Y");
    }

    $start_year = $year;
    $start_year_formated = str_pad(intval($start_year), 4, "0", STR_PAD_RIGHT);
    $end_year = $start_year + 1;
    $end_year_formated = str_pad(intval($end_year), 4, "0", STR_PAD_RIGHT);

    if(empty($month))
    {
        //只设置了年份
        $start_month_formated = '01';
        $end_month_formated = '01';
        $start_day_formated = '01';
        $end_day_formated = '01';
    }
    else
    {

        $month > 12 || $month < 1 ? $month = 1 : $month = $month;
        $start_month = $month;
        $start_month_formated = sprintf("%02d", intval($start_month));

        if(empty($day))
        {
            //只设置了年份和月份
            $end_month = $start_month + 1;

            if($end_month > 12)
            {
                $end_month = 1;
            }
            else
            {
                $end_year_formated = $start_year_formated;
            }
            $end_month_formated = sprintf("%02d", intval($end_month));
            $start_day_formated = '01';
            $end_day_formated = '01';
        }
        else
        {
            //设置了年份月份和日期
            $startTimestamp = strtotime($start_year_formated.'-'.$start_month_formated.'-'.sprintf("%02d", intval($day))." 00:00:00");
            $endTimestamp = $startTimestamp + 24 * 3600 - 1;
            return array('start' => $startTimestamp, 'end' => $endTimestamp);
        }
    }

    $startTimestamp = strtotime($start_year_formated.'-'.$start_month_formated.'-'.$start_day_formated." 00:00:00");
    $endTimestamp = strtotime($end_year_formated.'-'.$end_month_formated.'-'.$end_day_formated." 00:00:00") - 1;
    return array('start' => $startTimestamp, 'end' => $endTimestamp);
}

//随即一个字符串
function getRandChar($length)
{
    $str = null;
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max = strlen($strPol) - 1;

    for ($i = 0;$i < $length;$i++) {
        $str .= $strPol[rand(0, $max)];
    }
    return $str;
}

//将科学计数法转为字符
function numToStr($num)
{
    $result = "";
    if (stripos($num, 'e') === false) {
        return $num;
    }
    while ($num > 0) {
        $v = $num - floor($num / 10) * 10;
        $num = floor($num / 10);
        $result = $v . $result;
    }
    return $result;
}

/**
 * excel表格导出
 * @param string $fileName 文件名称
 * @param array $headArr 表头名称
 * @param array $data 要导出的数据
 * @author static
 */

function excelExport($fileName = '', $headArr = [], $data = []) {
    $fileName .= "_" . date("Y_m_d", Request::instance()->time()) . ".xls";
    $objPHPExcel = new \PHPExcel();
    $objPHPExcel->getProperties();
    $key = ord("A"); // 设置表头
    foreach ($headArr as $v) {
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        $key += 1;
    }
    $column = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();
    foreach ($data as $key => $rows) { // 行写入
        $span = ord("A");
        foreach ($rows as $keyName => $value) { // 列写入
            $objActSheet->setCellValue(chr($span) . $column, $value);
            $span++;
        }
        $column++;
    }
    $fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
    $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=$fileName");
    header('Cache-Control: max-age=0');
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output'); // 文件通过浏览器下载
    exit();
}
//遍历文件夹下的所有文件
function bianli1($dir)
{
    $files = array();
    $array = [];
    if($head = opendir($dir))
    {
        while(($file = readdir($head)) !== false)
        {
            if($file != ".." && $file!=".")
            {
                if(is_dir($file))
                {
                    $files['list'] = bianli1($dir.'/'.$file);
                    $info = explode('.',$files['list']);
                    $files['downloadName'] = $info[0];
                    $files['time'] = date("Y-m-d H:i:s",filectime(ROOT_PATH . 'public' . DS .'static'. DS .'data'.DS.$files['list']));
                    $files['size'] = round(filesize(ROOT_PATH . 'public' . DS .'static'. DS .'data'. DS .$files['list'])/(1024*1024),2);
                }
                else
                {
                    $files['list'] = $file;
                    $info = explode('.',$files['list']);
                    $files['downloadName'] = $info[0];
                    $files['time'] = date("Y-m-d H:i:s",filectime(ROOT_PATH . 'public' . DS .'static'. DS .'data/'.DS.$files['list']));
                    $files['size'] = round(filesize(ROOT_PATH . 'public' . DS .'static'. DS .'data'. DS .$files['list'])/(1024*1024),2);
                }
                $array[] = $files;
            }
        }
    }
    closedir($head);
    return $array;
}
